#include<stdio.h>
#include<pthread.h>
#include<sys/wait.h>
#include<unistd.h>
#include<sys/mman.h>

typedef struct obj {
	int num;
	pthread_mutex_t mtx;
	pthread_mutexattr_t mtx_attr;
}obj;
int main() {
	pthread_mutex_t mtx;
	pthread_mutexattr_t mtx_attr;

	pthread_mutexattr_init(&mtx_attr);
	// PTHREAD_PROCESS_PRIVATE 进程间私有，线程中共有。
	// PTHREAD_PROCESS_SHARED  进行成共有。
	pthread_mutexattr_setpshared(&mtx_attr, PTHREAD_PROCESS_SHARED);
	pthread_mutex_init(&mtx, &mtx_attr);

	obj *mm = (obj*)mmap(0, 1024, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);

	if (MAP_FAILED == mm) {
		perror("mmap");
		return 0;
	}
	mm->mtx = mtx;
	mm->mtx_attr = mtx_attr;

	int i;

	pid_t pid = fork();
	if (pid == 0) {
		for (i = 0; i < 100000; i++) {
			pthread_mutex_lock(&mm->mtx);
			mm->num ++;
			pthread_mutex_unlock(&mm->mtx);
		}
		return 0;
	}else if (pid >0) {
		for (i = 0; i< 100000; i++) {
			pthread_mutex_lock(&mm->mtx);
			mm->num ++;
			pthread_mutex_unlock(&mm->mtx);
		}
		wait(0);
		printf("num = %d\n", mm->num);
	}else{
		perror("fork error");
	}

	munmap(mm, 1024);
	pthread_mutexattr_destroy(&mtx_attr);
	return 0;
}
